package OptimalAlgorithm.Hash;

import java.util.HashMap;
//https://leetcode.cn/problems/two-sum/description/
public class TwoSum {
    //方法一：暴力解法
/*    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if(nums[i] + nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }
        return null;
    }*/
    //方法二：利用hash表
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> hash = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            //1、判断
            if(hash.containsKey(target - nums[i])){
                return new int[] {i,hash.get(target - nums[i])};
            }
            //2、将元素添加到hash表中
            hash.put(nums[i],i);
        }
        return null;
    }
    //提前将数存入hash表中
/*    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> hash = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            hash.put(nums[i],i);
        }
        for (int i = 0; i < nums.length; i++) {
            if(hash.containsKey(target - nums[i]) && hash.get(target - nums[i]) != i){
                return new int[]{i,hash.get(target - nums[i])};
            }
        }
        return null;
    }*/
}
